package org.example.iris.controller;

import org.example.iris.dto.Result;
import org.example.iris.entity.*;
import org.example.iris.service.CompanyService;
import org.example.iris.service.UserService;
import org.example.iris.utils.JwtUtil;
import org.example.iris.utils.Md5Util;
import org.example.iris.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    CompanyService companyService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/verifyCode")
    public Result verifyCode(@RequestBody Map<String, String> params) {
        if (userService.findByPhone(params.get("phoneNum")) != null) {
            return Result.error("手机号已绑定");
        }
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        if (ops.get(params.get("phoneNum")) == null || !params.get("code").equals(ops.get(params.get("phoneNum")))) {
            return Result.error("验证码错误");
        }
        return Result.success();
    }

    @PostMapping("/sendPhoneCode")
    public Result sendPhoneCode(@RequestBody Map<String, String> params) throws Exception {
        userService.sendPhoneCode(params.get("phoneNum"));
        return Result.success();
    }

    @PostMapping("/sendEmailCode")
    public Result sendEmailCode(@RequestBody Map<String, String> params) throws Exception {
        userService.sendEmailCode(params.get("email"));
        return Result.success();
    }

    @PostMapping("/login")
    public Result login(@RequestBody Map<String, String> params) {
//        User user = userService.findByUsername(username);
        User user = userService.findByPhone(params.get("phoneNum"));
        if (user == null) {
            return Result.error("用户不存在");
        }
        if (!user.getRole().equals(params.get("role"))) {
            return Result.error("角色错误");
        }
        if(user.getRole().equals("company")){
            Company company = companyService.findByUserId(user.getUserId());
            if(!company.isExaminePassed()){
                return Result.error("企业未通过审核");
            }
        }
        if(Md5Util.getMD5String(params.get("password")).equals(user.getPassword())){
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId", user.getUserId());
            claims.put("role", user.getRole());
            String token = JwtUtil.genToken(claims);

            ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
            ops.set(token, token, 6, TimeUnit.HOURS);

            return Result.success(token);
        }
        else {
            return Result.error("密码错误");
        }
    }

    @PatchMapping("/updatePassword")
    public Result updatePassword(@RequestBody Map<String, String> params, @RequestHeader("Authorization") String token) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer userId = (Integer) claims.get("userId");
        User user = userService.findById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }
        if (!params.get("newPassword").equals(params.get("reNewPassword"))) {
            return Result.error("两次密码不一致");
        }
        if (!user.getPassword().equals(Md5Util.getMD5String(params.get("password")))) {
            return Result.error("原密码错误");
        }
        user.setPassword(Md5Util.getMD5String(params.get("newPassword")));
        userService.updatePassword(user);

        //删除redis中的token
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ops.getOperations().delete(token);

        return Result.success();
    }

    @PatchMapping("updatePhone")
    public Result updatePhone(@RequestBody Map<String, String> params) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer userId = (Integer) claims.get("userId");
        String role = (String) claims.get("role");
        if (!role.equals("student")) {
            return Result.error("无权限");
        }

        if (userService.findByPhone(params.get("phoneNum")) != null) {
            return Result.error("手机号已绑定");
        }

        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        if (ops.get(params.get("phone")) == null || !params.get("code").equals(ops.get(params.get("phone")))) {
            return Result.error("验证码错误");
        }

        userService.updatePhone(params.get("phone"), userId);
        return Result.success();
    }

    @PatchMapping("updateEmail")
    public Result updateEmail(@RequestBody Map<String, String> params) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer userId = (Integer) claims.get("userId");
        String role = (String) claims.get("role");
        if (!role.equals("student")) {
            return Result.error("无权限");
        }

        if (userService.findByEmail(params.get("email")) != null) {
            return Result.error("邮箱已绑定");
        }

        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        if (ops.get(params.get("email")) == null || !params.get("code").equals(ops.get(params.get("email")))) {
            return Result.error("验证码错误");
        }

        userService.updateEmail(params.get("email"), userId);
        return Result.success();
    }
}

